<!--文件表格组件-->
<template>
  <div class="listedFiles">
    <!--    菜单页面-->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="文件名称" prop="tableName">
        <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable />
      </el-form-item>
      <el-form-item label="文号" prop="tableName" v-if="fileType !== '非持续审计模型'">
        <el-input v-model="queryParams.documentNo" placeholder="请输入文号" clearable />
      </el-form-item>
      <el-form-item label="制度层级" prop="tableName" v-if="fileType === '制度库'">
        <el-select v-model="queryParams.systemLevel" placeholder="请选择制度层级" style="width: 240px" clearable>
          <el-option :label="item" :value="item" v-for="item in INSTITUTIONAL_LEVEL" :key="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="归属条线" prop="tableName" v-if="fileType === '制度库'">
        <el-select v-model="queryParams.belongLine" placeholder="请选择归属条线" style="width: 240px" clearable>
          <el-option :label="item" :value="item" v-for="item in HOMING_LINE" :key="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="条线归类" prop="lineType" v-if="fileType === '考核情况'">
        <el-select v-model="queryParams.lineType" placeholder="请选择条线归类" style="width: 240px" clearable>
          <el-option :label="item" :value="item" v-for="item in LINE_CATEGORIZATION" :key="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否可建模" prop="tableName" v-if="fileType === '非持续审计模型'">
        <el-select v-model="queryParams.moduled" placeholder="请选择是否可建模" style="width: 240px" clearable>
          <el-option :label="item" :value="item" v-for="item in MODELING" :key="item" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="inquire">查询</el-button>
        <el-button type="success" icon="MessageBox" @click="exportFolders">导出</el-button>
        <el-button icon="Plus" @click="dialogVisible = true" v-if="administrator">新增</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
        <el-button icon="Download" @click="batchDownloads">批量下载</el-button>
      </el-form-item>
    </el-form>
    <!--    表格页面-->
    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column
        label="序号"
        type="index"
        width="80"
        align="center"
        :index="queryParams.pageNum * queryParams.pageSize - queryParams.pageSize + 1"
      >
      </el-table-column>
      <el-table-column label="文件名称" align="center" prop="fileName" :show-overflow-tooltip="true" />
      <el-table-column label="条线归类" align="center" prop="lineType" width="160" v-if="fileType === '考核情况'" />
      <el-table-column
        label="文号"
        align="center"
        prop="documentNo"
        :show-overflow-tooltip="true"
        v-if="fileType !== '非持续审计模型'"
      />
      <el-table-column
        label="制度层级"
        align="center"
        prop="systemLevel"
        :show-overflow-tooltip="true"
        v-if="fileType === '制度库'"
      />
      <el-table-column
        label="是否可建模"
        align="center"
        prop="moduled"
        :show-overflow-tooltip="true"
        v-if="fileType === '非持续审计模型'"
      />
      <el-table-column label="归属条线" align="center" prop="belongLine" width="160" v-if="fileType === '制度库'" />
      <el-table-column label="操作" align="center" width="330">
        <template #default="{ row }">
          <el-button type="warning" @click="preview(row.id)">查看</el-button>
          <el-button type="primary" @click="downloadFolders(row)">下载</el-button>
          <el-popconfirm title="是否确认删除此文件?" width="300" @confirm="deleteFolders(row.id)" v-if="administrator">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 新增界面 -->
    <el-dialog
      width="1000"
      v-model="dialogVisible"
      center
      title="新增"
      @close="dialogClose"
      align-center
      class="addedPopUpWindow"
    >
      <el-form :inline="true" :model="popUpForm" :rules="rules" label-width="auto" ref="ruleFormRef">
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="popUpForm.fileName" placeholder="请输入文件名称" clearable style="width: 300px" />
        </el-form-item>
        <el-form-item label="文号" prop="documentNo" v-if="fileType !== '非持续审计模型'">
          <el-input v-model="popUpForm.documentNo" placeholder="请输入文号" clearable style="width: 300px" />
        </el-form-item>
        <el-form-item label="制度层级" prop="systemLevel" v-if="fileType === '制度库'">
          <el-select v-model="popUpForm.systemLevel" placeholder="请选择" style="width: 300px" clearable>
            <el-option :label="item" :value="item" v-for="item in INSTITUTIONAL_LEVEL" :key="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属条线" prop="belongLine" v-if="fileType === '制度库'">
          <el-select v-model="popUpForm.belongLine" placeholder="请选择" style="width: 300px" clearable>
            <el-option :label="item" :value="item" v-for="item in HOMING_LINE" :key="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="条线归类" prop="lineType" v-if="fileType === '考核情况'">
          <el-select v-model="popUpForm.lineType" placeholder="请选择" style="width: 300px" clearable>
            <el-option :label="item" :value="item" v-for="item in LINE_CATEGORIZATION" :key="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否可建模" prop="moduled" v-if="fileType === '非持续审计模型'">
          <el-select v-model="popUpForm.moduled" placeholder="请选择是否可建模" style="width: 300px" clearable>
            <el-option :label="item" :value="item" v-for="item in MODELING" :key="item" />
          </el-select>
        </el-form-item>
        <!--        上传附件-->
        <el-form-item prop="fileList" class="uploadAttachments">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            drag
            action=""
            :auto-upload="false"
            :on-exceed="handleExceed"
            :on-change="handleChange"
            :on-remove="handleChange"
            :file-list="popUpForm.fileList"
            :show-file-list="true"
            :limit="MULTIPLE_CHOICES_TYPE.includes(fileType) ? 9 : 1"
            :http-request="upload"
            :multiple="MULTIPLE_CHOICES_TYPE.includes(fileType)"
          >
            <template #trigger>
              <el-button type="primary">上传附件</el-button>
            </template>
            <template #tip>
              <div>请上传 大小不超过 500MB 的文件</div>
            </template>
          </el-upload>
          <el-input v-model="popUpForm.fileList[0]" :hidden="true" style="width: 0" class="fileList" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="popUpCommit(ruleFormRef)"> 确 定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!--  查看弹窗-->
    <el-dialog v-model="checkOutTheList" title="查看全部附件" width="50%" center align-center class="viewPopUps">
      <el-table :data="checkOutTheListData" stripe max-height="800">
        <el-table-column label="序号" type="index" width="80" align="center"> </el-table-column>
        <el-table-column label="文件名称" align="center" prop="docName" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="330">
          <template #default="{ row }">
            <el-button type="success" @click="onlinePreview(row.id)">预览</el-button>
            <el-button type="primary" @click="download(row.id)">下载</el-button>
            <el-popconfirm title="是否确认删除此文件?" width="300" @confirm="deleteFile(row)" v-if="administrator">
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
const INSTITUTIONAL_LEVEL = ["法律法规及政策规定", "集团", "省公司"]; //制度层级
const HOMING_LINE = [
  "市场",
  "政企",
  "工程",
  "网络",
  "采购",
  "财务",
  "党群纪检",
  "规划",
  "规划(1)",
  "客服",
  "人力",
  "信安",
  "战法",
  "综合",
]; //归属条线
const MODELING = ["可建模", "不可建模"]; //是否可建模
const MULTIPLE_CHOICES_TYPE = ["制度库", "考核情况", "非持续审计模型"]; //多选类型
const LINE_CATEGORIZATION = ["经营业绩", "市场", "政企", "网络", "工程", "财务", "供管", "安全生产", "工会", "党建", "纪检"]; //条线归类
import { reactive } from "vue";
import { ElMessage, genFileId, ElLoading } from "element-plus";
import {
  deleteFileApi,
  deleteFoldersApi,
  downloadFoldersApi,
  exportFoldersApi,
  getAdministratorApi,
  getAttachmentIDApi,
  getDownloadTheFileApi,
  getNewFileApi,
  getPreviewFileApi,
  getQueryFileApi,
  getQueryFileListApi,
} from "@/api/backStageManagement";
const props = defineProps({
  fileType: {
    type: String, //文件类型
    required: true,
  },
});
const administrator = ref(false); //是否是管理员
// 判断是否是管理员
const getAdministrator = async () => {
  const data = await getAdministratorApi();
  administrator.value = data.data;
};
getAdministrator(); //判断是否是管理员
const tableList = ref([]); // 表格数据
const loading = ref(true); // 加载状态
const dialogVisible = ref(false); //弹窗状态
const ruleFormRef = ref(); //弹窗表单实列
const popUpForm = reactive({
  fileName: "", //文件名称
  systemLevel: "", //制度层级
  belongLine: "", //归属条线
  documentNo: "", //文号
  lineType: "", //条线归类
  fileList: [], //附件
  moduled: "", //是否可建模
}); // 弹窗表单数据
/**
 * 提取Excel文件名
 * @param fileName
 * @returns {string|null}
 */
function extractExcelBaseName(fileName) {
  // 使用正则表达式找到最后一个点（\.）及之后的所有字符（.*$），并替换为空字符串，从而移除扩展名
  return fileName.replace(/\.([^.]*)$/, "");
}
/**
 * 文件校验，当文件列表为空，附件清空
 * @param file
 * @param files
 */
const handleChange = (file, files) => {
  if (files.length) {
    popUpForm.fileList.push(files.length);
  } else {
    popUpForm.fileList = [];
  }
};
const rules = reactive({
  fileName: [{ required: true, message: "请输入文件名称", trigger: "blur" }],
  documentNo: [{ required: false }],
  systemLevel: [{ required: true, message: "请选择制度层级", trigger: "change" }],
  belongLine: [{ required: true, message: "请输入归属条线", trigger: "change" }],
  lineType: [{ required: true, message: "请输入条线归类", trigger: "change" }],
  fileList: [{ required: true, message: "请上传文件", trigger: "blur" }],
  moduled: [{ required: true, message: "请选择是否可建模", trigger: "change" }],
}); //表单校验
const total = ref(0); //总条数
const queryParams = reactive({
  pageNum: 1, //当前页码
  pageSize: 10, //每页条数
  fileName: null, //文件名称
  systemLevel: null, //制度层级
  belongLine: null, //归属条线
  documentNo: null, //文号
  lineType: "", //条线归类
  moduled: null, //是否可建模
  cover: !MULTIPLE_CHOICES_TYPE.includes(props.fileType), //是否多文件
});
// 查询操作
const inquire = async () => {
  const data = await getQueryFileApi({
    fileType: props.fileType,
    ...queryParams,
  });
  loading.value = false;
  tableList.value = data.rows;
  total.value = data.total;
};
const batchDownloadOption = ref([]); //批量下载选项ID
// 当选项发生变化时, 将选中的选项ID存储到 batchDownloadOption 中
const handleSelectionChange = (value) => {
  batchDownloadOption.value = value.map((item) => item.id);
};
// 批量下载
const batchDownloads = async () => {
  //当没选择选项时，提示选择
  if (batchDownloadOption.value.length === 0) {
    ElMessage.warning("请选择要下载的文件");
    return;
  }
  const data = await downloadFoldersApi(batchDownloadOption.value);
  downLoad(data, props.fileType, "application/zip,charset=UTF-8");
};
// 导出表格列表
const exportFolders = async () => {
  const data = await exportFoldersApi({
    fileType: props.fileType,
    ...queryParams,
  });
  downLoad(data, props.fileType, "application/vnd.ms-excel,charset=UTF-8");
};
// 重置操作
const reset = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    fileName: null,
    systemLevel: null,
    belongLine: null,
    documentNo: null,
    moduled: null,
  });
  inquire();
};
const loadingInstance = ref(null); // loding实例
const formData = ref(new FormData()); //
/**
 * 上传文件
 * @param file 文件列表
 * @returns {Promise<void>}
 */
const upload = async (file) => {
  formData.value.append("file", file.file);
};
const uploadRef = ref(); //上传组件实列
/**
 * 自动覆盖上一个文件
 * @param files
 */
const handleExceed = (files) => {
  if (MULTIPLE_CHOICES_TYPE.includes(props.fileType)) {
    return;
  }
  uploadRef.value.clearFiles();
  const file = files[0]; //获取上传的文件
  file.uid = genFileId();
  uploadRef.value.handleStart(file);
};
//弹窗提交
const popUpCommit = async (valid) => {
  /**
   * 校验表单
   * 本函数无参数和返回值，主要用于触发并校验名为 ruleFormRef 的表单。
   */
  if (!valid) {
    // 如果表单当前状态无效，则直接返回，不进行后续校验
    return;
  }
  await ruleFormRef.value.validate(async (valid) => {
    // 异步校验表单
    if (valid) {
      // 如果表单验证通过
      uploadRef.value.submit();
      try {
        loadingInstance.value = ElLoading.service({ fullscreen: true, text: "文件上传中，请稍后" });
        const attachmentID = await getAttachmentIDApi({
          fileType: props.fileType,
        }); //先拿到当前页面的文件夹ID
        const { fileName, systemLevel, lineType, moduled, documentNo, belongLine } = popUpForm;
        const docInfo = {
          folderId: attachmentID.data.folderId, //文件夹ID
          fileName, //文件名称
          documentNo, //文号
          systemLevel, //制度层级
          belongLine, //归属条线
          lineType, //归属条线
          fileType: props.fileType, //文件类型
          moduled, //是否可建模
          cover: "false", //是否覆盖
        };
        formData.value.append("docInfo", JSON.stringify(docInfo));
        await getNewFileApi(formData.value); //上传文件
        ElMessage.success("文件上传成功");
        await inquire(); //更新文件列表
      } catch (error) {
        ElMessage({
          dangerouslyUseHTMLString: true,
          showClose: true,
          message: error.replace("<br/>", ""), //删除第一个换行符
          type: "error",
          duration: 5000,
        });
      } finally {
        loadingInstance.value.close();
        dialogVisible.value = false;
      }
    }
  });
};
//弹窗关闭初始化表单
const dialogClose = () => {
  ruleFormRef.value.resetFields();
};
const checkOutTheList = ref(false); //查看弹窗状态
const checkOutTheListData = ref([]); //查看弹窗数据
//查看按钮
const preview = async (id) => {
  const { rows } = await getQueryFileListApi(id);
  checkOutTheListData.value = rows;
  checkOutTheList.value = true;
};
// 文件夹下载
const downloadFolders = async (row) => {
  const data = await downloadFoldersApi([row.id]);
  downLoad(data, row.fileName, "application/zip,charset=UTF-8");
};
/**
 * 文件流下载
 * @param data
 * @param fileName
 * @param type 文件流格式
 */
const downLoad = (data, fileName, type) => {
  const blob = new Blob([data], { type });
  const href = window.URL.createObjectURL(blob);
  // 兼容 ie
  const link = document.createElement("a");
  link.style.display = "none";
  link.href = href;
  link.download = decodeURIComponent(fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(link);
};
//在线预览
const onlinePreview = async (id) => {
  const { msg } = await getPreviewFileApi(id);
  window.open(msg, "_blank");
};
//下载文件
const download = async (id) => {
  const { msg } = await getDownloadTheFileApi(id);
  window.open(msg, "_blank");
};
//删除文件
const deleteFile = async (row) => {
  try {
    // 删除文件API调用
    await deleteFileApi(row.id);
    // 显示文件删除成功的消息
    ElMessage.success("文件删除成功");
    // 进行查询操作
    await preview(row.attachmentId);
  } catch (error) {
    ElMessage.error("操作失败，请稍后重试");
  }
};
// 批量删除文件夹
const deleteFolders = async (id) => {
  try {
    // 删除文件夹API调用
    await deleteFoldersApi([id]);
    // 显示文件删除成功的消息
    ElMessage.success("文件删除成功");
    // 进行查询操作
    await inquire();
  } catch (error) {
    ElMessage.error("操作失败，请稍后重试");
  }
};
// 分页操作
const getList = (value) => {
  queryParams.pageNum = value.page;
  queryParams.pageSize = value.limit;
  inquire();
};
onMounted(() => {
  inquire(); // 查询操作
});
</script>
<style lang="less" scoped>
.listedFiles {
  padding: 20px;
  .upload-demo {
    :deep(.el-upload) {
      --el-upload-dragger-padding-horizontal: 0;
      --el-upload-dragger-padding-vertical: 0;
      .el-upload-dragger {
        border: none;
        text-align: start;
      }
    }
  }
  :deep(.fileList) {
    .el-input__wrapper {
      box-shadow: none;
    }
  }
  :deep(.el-overlay-dialog) {
    .addedPopUpWindow {
      border-radius: 15px;
      margin-top: auto !important;
      .el-dialog__header {
        .el-dialog__headerbtn {
          font-size: 20px;
        }
      }
      .el-dialog__body {
        form.el-form.el-form--default.el-form--label-right.el-form--inline {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          .el-form-item {
            margin-right: 0;
          }
          .uploadAttachments {
            width: 700px;
            .upload-demo {
              flex: 1;
            }
          }
        }
      }
    }
  }
}
</style>
<style lang="less">
.el-overlay-dialog {
  .viewPopUps {
    border-radius: 15px;
    margin-top: auto !important;
    .el-dialog__header {
      .el-dialog__headerbtn {
        font-size: 20px;
      }
    }
  }
}
</style>
